# coding: UTF-8
# @Date    ：2024/10/14 17:52 
# @File    : __init__.py
# :Author:  fum
import os

from flask import Flask
from pydantic_settings import SettingsConfigDict

from libs import PrintUtils
from libs.path import PathUtil
from .system import SystemConfig
from .system.db_config import DatabaseConfigSettings
from .system.system_config import SystemConfigSettings


class Settings(
    SystemConfig,
):
    """所有配置 优先使用环境变量映射配置 其次使用配置文件映射配置"""
    model_config = SettingsConfigDict(
        env_file=PathUtil.get_env(),
        env_file_encoding="utf-8",
        frozen=True,
        # ignore allow forbid
        extra="allow",
        # case sensitive 默认False 大小写铭感
        case_sensitive=True,
    )


APP: Flask
CONFIG: dict


class ConfigManager:

    @staticmethod
    def set_config(dic: dict):
        """添加其他配置"""
        global CONFIG
        for key, value in dic.items():
            CONFIG.setdefault(key, value)
            APP.config[key] = value

    @staticmethod
    def init_config(app):
        """初始化配置"""
        # settings = Settings(**config)  加载yml配置文件 , 但是需要定义多层配置不方便查看 暂不实现
        config_dict = ConfigManager.init_config_config()
        ConfigManager.init_app_config(app, config_dict)
        PrintUtils.print_colored(f"配置初始化成功 : 【{PathUtil.get_env()}】")
        PrintUtils.print_fancy_data([APP.config], "APP")
        PrintUtils.print_fancy_data([CONFIG], "CONFIG")

    @staticmethod
    def init_config_config():
        """初始化纯配置"""
        global CONFIG
        all_config = Settings()
        config_dict = all_config.model_dump()
        CONFIG = config_dict
        return config_dict

    @staticmethod
    def init_app_config(app: Flask, config_dict: dict):
        """加载配置到flask 和 os.environ"""
        global APP
        APP = app
        for key, value in config_dict.items():
            if isinstance(value, str):
                os.environ[key] = value
                APP.config[key] = value
            elif isinstance(value, int | float | bool):
                os.environ[key] = str(value)
                APP.config[key] = value
            elif value is None:
                os.environ[key] = ""
                APP.config[key] = ""
